package com.lewis.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Component;

import com.lewis.jpa.entity.BaseEntity;
@Component("lewisJPA")
public class AbstractJPADAO<ENTITY extends BaseEntity<?>> {
	
	@PersistenceContext(unitName = "lewisJPA")
	private EntityManager entityManager;
	
	@PersistenceContext(unitName = "extraJPA")
	private EntityManager extraEntityManager;
	
	//TODO: Overload persist method if multi-datasource is involved
	public void save(ENTITY entity) {
		entityManager.persist(entity);
	}

	public void saveALL(List<ENTITY> entities) {
		entityManager.setFlushMode(FlushModeType.COMMIT);
		for (ENTITY t : entities) {
			entityManager.persist(t);
		}
		// TODO: flush when it's necessary
	}

	public void update(ENTITY entity) {
		entityManager.merge(entity);
	}

	public void updateALL(List<ENTITY> entities) {
		entityManager.setFlushMode(FlushModeType.COMMIT);
		for (ENTITY t : entities) {
			entityManager.merge(t);
		}
		// TODO: flush when it's necessary
	}

	public <EntityClass, ID> EntityClass loadById(
			Class<EntityClass> entityClass, ID id) {
		return entityManager.find(entityClass, id);
	}

	public void delete(ENTITY entity) {
		// TODO Auto-generated method stub

	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getExtraEntityManager() {
		return extraEntityManager;
	}

	public void setExtraEntityManager(EntityManager extraEntityManager) {
		this.extraEntityManager = extraEntityManager;
	}

}
